package com.ruoyi.bussiness.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import com.ruoyi.bussiness.domain.*;
import com.ruoyi.bussiness.domain.setting.AddMosaicSetting;
import com.ruoyi.bussiness.domain.setting.Setting;
import com.ruoyi.bussiness.mapper.TAppUserMapper;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.CachePrefix;
import com.ruoyi.common.enums.RecordEnum;
import com.ruoyi.common.enums.SettingEnum;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.OrderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.bussiness.mapper.TAiFollowOrdersMapper;
import com.ruoyi.bussiness.service.ITAiFollowOrdersService;

import javax.annotation.Resource;

/**
 * 跟投订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-16
 */
@Service
public class TAiFollowOrdersServiceImpl extends ServiceImpl<TAiFollowOrdersMapper,TAiFollowOrders> implements ITAiFollowOrdersService
{
    @Autowired
    private TAiFollowOrdersMapper tAiFollowOrdersMapper;
    @Resource
    private TAppUserMapper appUserMapper;
    @Resource
    private RedisCache redisCache;

    /**
     * 查询跟投订单
     * 
     * @param id 跟投订单主键
     * @return 跟投订单
     */
    @Override
    public TAiFollowOrders selectTAiFollowOrdersById(String id)
    {
        return tAiFollowOrdersMapper.selectTAiFollowOrdersById(id);
    }

    /**
     * 查询跟投订单列表
     * 
     * @param tAiFollowOrders 跟投订单
     * @return 跟投订单
     */
    @Override
    public List<TAiFollowOrders> selectTAiFollowOrdersList(TAiFollowOrders tAiFollowOrders)
    {
        return tAiFollowOrdersMapper.selectTAiFollowOrdersList(tAiFollowOrders);
    }

    /**
     * 新增跟投订单
     * 
     * @param tAiFollowOrders 跟投订单
     * @return 结果
     */
    @Override
    public int insertTAiFollowOrders(TAiFollowOrders tAiFollowOrders)
    {
        return tAiFollowOrdersMapper.insertTAiFollowOrders(tAiFollowOrders);
    }

    @Override
    public String createFollowOrder(TAiFollowOrders order) {
//        log.info("下单"+ JSONObject.toJSONString(order));
        try{
            String serialId = "R" + OrderUtils.generateOrderNum();
            long loginIdAsLong = StpUtil.getLoginIdAsLong();
            BigDecimal amount = order.getInvestAmount();
            TAppUser user = appUserMapper.selectTAppUserByUserId(loginIdAsLong);

            //1. 时间判断， 不能太频繁

//            // 平台资产
//            Map<String, TAppAsset> assetMap=assetService.getAssetByUserIdList(user.getUserId());
//            TAppAsset asset=assetMap.get(order.getBaseSymbol().toLowerCase()+user.getUserId());
//            if ( asset.getAvailableAmount().compareTo(amount) < 0) {
//                return MessageUtils.message("order_amount_error");
//            }
            //根据ID 查看时间 周期

            //下单
            Date date = new Date();
//            order.setRate(secondPeriodConfig.getOdds());
//            order.setType(secondPeriodConfig.getPeriod().intValue());
//            order.setRateFlag(secondPeriodConfig.getFlag());
            order.setUserId(user.getUserId().toString());
            order.setOrderNo(serialId);
            order.setCreateTime(date);
//            order.setCloseTime(date.getTime()+(order.getType()-2)* 1000L);//60秒后的时间)
//            order.setUserAddress(user.getAddress());
            order.setStatus(0);
//            order.setBetAmount(order.getBetAmount());
//            order.setRewardAmount(BigDecimal.ZERO);
//            //当前币种最新价格
//            BigDecimal price = redisCache.getCacheObject(CachePrefix.CURRENCY_PRICE.getPrefix() + order.getCoinSymbol().toLowerCase());
//            TSecondCoinConfig one = tSecondCoinConfigMapper.selectOne(new LambdaQueryWrapper<TSecondCoinConfig>().eq(TSecondCoinConfig::getCoin, order.getCoinSymbol().toUpperCase()));
//            if(one != null && 2!=one.getType()){
//                price=redisCache.getCacheObject(CachePrefix.CURRENCY_PRICE.getPrefix() + order.getCoinSymbol().toUpperCase());
//            }
//            order.setOpenPrice(price);
//            order.setSign(0);
//            order.setManualIntervention(1);
//            order.setAdminParentIds(user.getAdminParentIds());
//            //先扣钱，再下单
//            if (redisCache.tryLock(CachePrefix.USER_WALLET.getPrefix() + user.getUserId(), user.getUserId(), 1000)) {
//                //成功的情况下才进行加锁限制
//                if (!redisCache.hasKey(CachePrefix.ORDER_SECOND_CONTRACT.getPrefix() + user.getUserId())) {
//                    redisCache.setCacheObject(CachePrefix.ORDER_SECOND_CONTRACT.getPrefix() + user.getUserId(), serialId, 10000, TimeUnit.MILLISECONDS);
//                } else {
//                    return MessageUtils.message("order_10s_retry");
//                }
//                BigDecimal availableAmount = asset.getAvailableAmount();
//                asset.setAmout(asset.getAmout().subtract(amount));
//                asset.setAvailableAmount(availableAmount.subtract(amount));
//                assetService.updateByUserId(asset);
//                appWalletRecordService.generateRecord(user.getUserId(), amount, RecordEnum.OPTION_BETTING.getCode(), user.getLoginName(), serialId, RecordEnum.OPTION_BETTING.getInfo(), availableAmount, availableAmount.subtract(amount),order.getBaseSymbol(),user.getAdminParentIds());
                this.insertTAiFollowOrders(order);
//                log.debug("下注提交成功, userId:{}, orderId:{}, money:{}", user.getUserId(), serialId, "amount");

//                //秒合约打码
//                Setting setting = settingService.get(SettingEnum.ADD_MOSAIC_SETTING.name());
//                if (Objects.nonNull(setting)){
//                    AddMosaicSetting addMosaic = JSONUtil.toBean(setting.getSettingValue(), AddMosaicSetting.class);
//                    if (Objects.nonNull(addMosaic) && Objects.nonNull(addMosaic.getIsOpen()) && addMosaic.getIsOpen() && Objects.nonNull(addMosaic.getSencordIsOpen()) && addMosaic.getSencordIsOpen()){
//                        user.setTotleAmont(user.getTotleAmont().add(order.getBetAmount()));
//                        appUserMapper.updateTotleAmont(user);
//                    }
//                }

                return String.valueOf(order.getId());
//            }else {
//                return MessageUtils.message("withdraw.refresh");
//            }
        }catch (Exception e){
//            log.info(JSONObject.toJSONString(e));
            log.debug(JSONObject.toJSONString(e));
        }
        return  MessageUtils.message("withdraw.refresh");
    }

    /**
     * 修改跟投订单
     * 
     * @param tAiFollowOrders 跟投订单
     * @return 结果
     */
    @Override
    public int updateTAiFollowOrders(TAiFollowOrders tAiFollowOrders)
    {
        return tAiFollowOrdersMapper.updateTAiFollowOrders(tAiFollowOrders);
    }

    /**
     * 批量删除跟投订单
     * 
     * @param ids 需要删除的跟投订单主键
     * @return 结果
     */
    @Override
    public int deleteTAiFollowOrdersByIds(String[] ids)
    {
        return tAiFollowOrdersMapper.deleteTAiFollowOrdersByIds(ids);
    }

    /**
     * 删除跟投订单信息
     * 
     * @param id 跟投订单主键
     * @return 结果
     */
    @Override
    public int deleteTAiFollowOrdersById(String id)
    {
        return tAiFollowOrdersMapper.deleteTAiFollowOrdersById(id);
    }
}
